package com.jltx.xq.simplewatch.video.model.impl;

import android.text.TextUtils;

import com.jltx.xq.simplewatch.db.helper.NewsRecordDBHelper;
import com.jltx.xq.simplewatch.db.helper.NewsStateDBHelper;
import com.jltx.xq.simplewatch.news.model.bean.NewsRecord;
import com.jltx.xq.simplewatch.news.model.bean.NewsState;
import com.jltx.xq.simplewatch.news.model.bean.TopicNews;
import com.jltx.xq.simplewatch.news.model.bean.TopicNewsEntity;
import com.jltx.xq.simplewatch.news.model.impl.WeChatNewsModelImpl;
import com.jltx.xq.simplewatch.utils.GsonFactoryUtils;
import com.jltx.xq.simplewatch.utils.ListUtils;
import com.jltx.xq.simplewatch.video.model.ITopicLocalNewsModel;
import com.jltx.xq.simplewatch.video.model.ITopicNewsModel;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import cn.jltx.utils.XqLog;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2017/09/05.
 */

public class TopicNewsLocalModelImpl implements ITopicNewsModel,ITopicLocalNewsModel{

    private Integer lastNewsRecordPage; //缓存当前本地数据库上拉后的最后一组新闻数据的页码

    @Override
    public Observable<TopicNewsEntity> getTopicNews(String channel, boolean isDown) {
        if(!isHadCacheNewsRecord()){
            lastNewsRecordPage = 0;
            XqLog.d(TopicNewsModelImpl.TAG, "第一次进入页面加载上次最后的一页"+Thread.currentThread());
            return getLastNewsRecord(channel);
        }else {
            XqLog.d(WeChatNewsModelImpl.TAG, "上拉加载上一页新闻数据"+Thread.currentThread());
            return getNewsRecord(channel,lastNewsRecordPage - 1).delay(800, TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public Integer getLastNewsRecordPage() {
        return lastNewsRecordPage;
    }

    @Override
    public boolean isHadCacheNewsRecord() {
        boolean isHad;
        if(lastNewsRecordPage == null){
            isHad = false;
        }else {
            isHad = true;
        }
        return isHad;
    }

    /**
     * 刚运行程序第一次进页面时把上一次page为最大页面的新闻数据从数据库里面读取
     * @param channel
     * @return
     */
    public Observable<TopicNewsEntity> getLastNewsRecord(final String channel){
        Observable<TopicNewsEntity> lastNewsRecordObservalbe = Observable.create(new ObservableOnSubscribe<NewsRecord>() {
            @Override
            public void subscribe(ObservableEmitter<NewsRecord> e) throws Exception {
                XqLog.d(TopicNewsModelImpl.TAG, "刚进页面第一次加载数据库里页码为最大的新闻数据"+Thread.currentThread());
                NewsRecord newsRecord = NewsRecordDBHelper.getLastNewsRecordNoNull(channel); //根据频道名获取上一次page为最大页面的新闻数据
                e.onNext(newsRecord);
                e.onComplete();  //onnext之后记得一定要调用onComplete
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Consumer<NewsRecord>() {
            @Override
            public void accept(@NonNull NewsRecord newsRecord) throws Exception {
                XqLog.d(TopicNewsModelImpl.TAG, "将由数据库加载进来页码为最大的新闻数据的页码缓存到lastNewsRecordPage变量" + Thread.currentThread());
                if (newsRecord != null && newsRecord.getPage() != 0) {
                    lastNewsRecordPage = newsRecord.getPage();
                } else {
                    XqLog.d(TopicNewsModelImpl.TAG, "newsRecord  had no data");
                }
            }
        })
        .observeOn(Schedulers.io())
        .map(new Function<NewsRecord, TopicNewsEntity>() {
            @Override
            public TopicNewsEntity apply(@NonNull NewsRecord newsRecord) throws Exception {
                XqLog.d(TopicNewsModelImpl.TAG, "将由数据库加载进来页码为最大的新闻数据解析成新闻的列表" + Thread.currentThread());
                TopicNewsEntity topicNewsEntity = new TopicNewsEntity();
                if(newsRecord != null && !TextUtils.isEmpty(newsRecord.getData())){
                    try {
                        topicNewsEntity = GsonFactoryUtils.providerGson().fromJson(newsRecord.getData(),TopicNewsEntity.class);
                        if(!ListUtils.isEmpty(topicNewsEntity.new_list)){
                            Iterator<TopicNews> iterator = topicNewsEntity.new_list.iterator();
                            TopicNews topicNews;
                            while(iterator.hasNext()){
                                topicNews = iterator.next();
                                if(!TextUtils.isEmpty(topicNews.getTitle())){
                                    NewsState newsState = NewsStateDBHelper.getNewsState(channel, topicNews.getItem_id() + "/" + topicNews.getGroup_id() + "/" + topicNews.getUrl()); //key的规则:item_id/group_id/url
                                    if (newsState != null) {
                                        topicNews.setIsRead(newsState.getIs_read()); //设置到已经存在的新闻bean里面
                                        topicNews.setIsDel(newsState.getIs_del());
                                    }
                                }else {
                                    iterator.remove();
                                }

                            }
                            XqLog.d(TopicNewsModelImpl.TAG, "新闻列表不为空");
                        }
                    }catch (Exception e){
                        XqLog.d(TopicNewsModelImpl.TAG, "parser erro for news record");
                    }

                }
                return topicNewsEntity;
            }
        });
        return lastNewsRecordObservalbe;
    }

    /**
     * 上拉时去新闻数据库里面取上一页对应的新闻数据
     * @param channel
     * @param page
     * @return
     */
    public Observable<TopicNewsEntity> getNewsRecord(final String channel, final int page){
        Observable<TopicNewsEntity> lastNewsRecordObservalbe = Observable.create(new ObservableOnSubscribe<NewsRecord>() {
            @Override
            public void subscribe(ObservableEmitter<NewsRecord> e) throws Exception {
                XqLog.d(WeChatNewsModelImpl.TAG, "开始加载本地对应页面的数据"+Thread.currentThread());
                NewsRecord newsRecord = NewsRecordDBHelper.getNewsRecordNoNull(channel, page); //根据频道channel和page获取对应页面的新闻数据
                e.onNext(newsRecord);
                e.onComplete();  //onnext之后记得一定要调用onComplete
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(new Consumer<NewsRecord>() {
            @Override
            public void accept(@NonNull NewsRecord newsRecord) throws Exception {
                XqLog.d(TopicNewsModelImpl.TAG, "将由数据库加载进来的最新新闻数据的页码缓存到lastNewsRecordPage变量" + Thread.currentThread());
                if (newsRecord != null && newsRecord.getPage() != 0 && newsRecord.getPage() == page) {
                    lastNewsRecordPage = newsRecord.getPage();
                } else {
                    XqLog.d(TopicNewsModelImpl.TAG, "newsRecord  had no data");
                }
            }
        })
        .observeOn(Schedulers.io())
        .map(new Function<NewsRecord, TopicNewsEntity>() {
            @Override
            public TopicNewsEntity apply(@NonNull NewsRecord newsRecord) throws Exception {
                XqLog.d(TopicNewsModelImpl.TAG, "开始加载本地对应页面的数据" + Thread.currentThread());
                TopicNewsEntity topicNewsEntity = new TopicNewsEntity();
                if(newsRecord != null && !TextUtils.isEmpty(newsRecord.getData())){
                    try {
                        topicNewsEntity = GsonFactoryUtils.providerGson().fromJson(newsRecord.getData(),TopicNewsEntity.class);
                        if(!ListUtils.isEmpty(topicNewsEntity.new_list)){
                            for (TopicNews topicNews : topicNewsEntity.new_list){
                                NewsState newsState = NewsStateDBHelper.getNewsState(channel, topicNews.getItem_id() + "/" + topicNews.getGroup_id() + "/" + topicNews.getUrl()); //key的规则:item_id/group_id/url
                                if (newsState != null) {
                                    topicNews.setIsRead(newsState.getIs_read()); //设置到已经存在的新闻bean里面
                                    topicNews.setIsDel(newsState.getIs_del());
                                }
                            }
                            XqLog.d(TopicNewsModelImpl.TAG, "新闻列表不为空");
                        }
                    }catch (Exception e){
                        XqLog.d(TopicNewsModelImpl.TAG, "parser erro for news record");
                    }

                }
                return topicNewsEntity;
            }
        });

        return lastNewsRecordObservalbe;
    }

}
